//
// Created by Administrator on 2025/9/18.
//

#include "../Header/MyString.h"
#include<cstring>

MyString::MyString(const char * str){

    //  字符串虽然是引用传递，但需要拷贝，使其效果与值传递相等

    if(str == NULL){
        _str = new char[1];
        *_str = '\0';
    }
    else{
        int len = strlen(str);
        _str = new char[len + 1];
        strcpy(_str, str);
    }
}

MyString::~MyString(){
    delete []_str;
}

MyString::MyString(const MyString & other){
    int len = strlen(other._str);
    this->_str = new char[len+1];
    strcpy(this->_str, other._str);
}

MyString & MyString::operator = (const MyString & another){
    if(this == &another)
        return *this;
    else{
        delete []this->_str;
        int len = strlen(another._str);
        this->_str = new char[len + 1];
        strcpy(this->_str, another._str);
        return *this;
    }
}


MyString MyString::operator + (const MyString & other) {
    int len = strlen(this->_str) + strlen(other._str);
    MyString str;
    delete []str._str;

    str._str = new char[len+1];
    memset(str._str, 0, len + 1);

    strcat(str._str, this->_str);
    strcat(str._str, other._str);

    return str;
}

bool MyString::operator == (const MyString & other) {
    if(strcmp(this->_str, other._str) == 0)
        return true;
    else
        return false;
}

bool MyString::operator > (const MyString & other) {
    if(strcmp(this->_str, other._str) > 0)
        return true;
    else
        return false;
}

bool MyString::operator < (const MyString & other){
    if(strcmp(this->_str, other._str) < 0)
        return true;
    else
        return false;
}

char & MyString::operator [](int index){
    return _str[index];
}


